#pragma once

#include <iostream>
#include <unordered_map>
#include <fstream>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace LogModule;

const std::string defaultPath="./dictionary.txt";
const std::string sep=" : ";

//接收中文并转换为英文单词
class Dict
{
public:
    Dict(const std::string&path=defaultPath):_path(path)
    {}

    //加载词典到哈希表内，使用时直接查询
    bool LoadDictionary()
    {
        std::ifstream in(_path);
        if(!in.is_open())
        {
            LOG(FATAL)<<"open "<< _path << " error ";
            return false;
        }
        std::string line;
        while(std::getline(in,line))
        {
            
            if(line.empty())continue;
            
            auto pos = line.find(sep);
            if(pos==std::string::npos)
            {
                LOG(ERROR)<<"analysis " << line << "error";
                continue;
            }
            
            std::string english=line.substr(0,pos);
            std::string chinese=line.substr(pos+sep.size());
            if(english.empty()||chinese.empty())
            {
                LOG(ERROR)<<"key-value format " << __LINE__ << "error";
                continue;
            }
            // Dictionary[chinese]=english;
            Dictionary.insert(std::make_pair(english,chinese));
            LOG(INFO)<<"LOADING...  "<<line;
        }
        in.close();
        return true;
    }

    std::string Translate(const std::string& word,InetAddr&client)
    {
        auto it=Dictionary.find(word);
        if(it==Dictionary.end())
        {
            LOG(ERROR)<<"进入了翻译模块"<<"["<<client.IP()<<" : "<<client.PORT() <<"]"<<" None";
            return "None";
        }
        LOG(INFO)<<"进入了翻译模块"<<"["<<client.IP()<<" : "<<client.PORT() <<"]"<<it->first;
        return it->second;
    }

    ~Dict()
    {}
private:
    std::string _path;
    std::unordered_map<std::string,std::string> Dictionary;
};